from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse


# 添加自定义管理器
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,
                     self).get_queryset().filter(status='published')


# 帖子类
class Post(models.Model):
    objects = models.Manager()  # The default manager.  默认管理器
    published = PublishedManager()  # Our custom manager  自定义的管理器

    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    title = models.CharField('帖子标题', max_length=250)
    slug = models.SlugField('构建连接使用', max_length=250,
                            unique_for_date='publish') # 和时间字段 publish一起构成唯一
    author = models.ForeignKey(User,
                               related_name='blog_posts')
    body = models.TextField('帖子内容')
    publish = models.DateTimeField('发帖时间', default=timezone.now)
    created = models.DateTimeField('创建帖子的时间', auto_now_add=True)
    updated = models.DateTimeField('修改时间', auto_now=True)
    status = models.CharField('帖子当前状态', max_length=10,
                              choices=STATUS_CHOICES,
                              default='draft')

    class Meta:
        ordering = ('-publish',)  # 这里可以设置排序和权限等

    def __str__(self):
        return self.title

    # 添加获取动态连接的方法
    def get_absolute_url(self):
        return reverse('blog:post_detail',
                       args=[self.publish.year,
                             self.publish.strftime('%m'),
                             self.publish.strftime('%d'),
                             self.slug])
